// pages/SCM/store/goods/goods.js
const app = getApp()
const util = require('../../../../utils/util.js')
const lbbService = require('../../../service/service.js')
const printUtil = require('../../../../utils/hprt_blue_print_util.js')

Page({

  /**
   * 页面的初始数据
   */
  data: {
    goods: [],
    categories: [],
    tabNum: 0,
    pageNum: 1,
    pageSize: 15,
    goodsApplyList: [],
    applyStatus: [{
        id: 0,
        name: '待备货',
        num: 0
      }, {
        id: 1,
        name: '待收货',
        num: 0
      },
      {
        id: 2,
        name: '已收货',
        num: 0
      }, {
        id: 3,
        name: '已关闭',
        num: 0
      }
    ],
    sufNum: 1,
    hideFlag: true,
    printSleAddr: "收货地址",
    printSelApply: "申请物品",
    items: [{
        name: "收货地址",
        checked: true,
        value: "收货地址"
      },
      {
        name: "申请物品",
        checked: true,
        value: "申请物品"
      }
    ],
    printSelContents: ["收货地址", "申请物品"],
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    this.setData({
      scrollHeight: app.getScrollHeight(0)
    })
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {
    let that = this
    that.toast = that.selectComponent("#toast")
    this.personalModal = this.selectComponent("#personalModal")
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    let that = this
    this.goodsApplyStockList();

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  stockUpItem: function (e) {
    let item = e.currentTarget.dataset.item
    let tabNum = this.data.tabNum
    wx.navigateTo({
      url: '../goodsApplyItem/goodsApplyItem?id=' + item.id + '&stat=' + tabNum,
    })


  },

  toggleTab: function (e) {
    let id = e.currentTarget.dataset.id;
    if (id == this.data.tabNum) {
      id = '';
    }
    this.setData({
      tabNum: id,
      pageNum: 1
    });
    this.goodsApplyStockList();

  },
  getMore: function () {
    this.data.pageNum += 1;
    this.goodsApplyStockList();
  },
  getFirst: function () {
    this.data.pageNum == 1;
    this.goodsApplyStockList();
  },
  goodsApplyStockList: function () {
    let that = this;
    let params = {};
    params.applyStatus = that.data.tabNum;
    params.pageNum = that.data.pageNum;
    params.pageSize = that.data.pageSize;

    lbbService.goodsApplyStockList(params, function (res) {

      let goodsApplyList = res.data.goodsApplyList;
      let countMap = res.data.countApplyStatusMap;
      if (goodsApplyList && goodsApplyList.length > 0) {
        goodsApplyList.forEach(e => {
          //申请明细
          let details = e.goodsAccessDetails;
          let strs = [];
          details.forEach(item => {
            strs.push(item.goods.name + ' X' + item.goodsNum);
          })
          let str = strs.join('、');
          e.goodsStrs = str;
          //备货明细
          let goodsApplyUps = e.goodsApplyUps;
          let packs = [];
          goodsApplyUps.forEach((item, i) => {
            let pack = {};
            pack.packName = '包裹' + (i + 1);
            pack.packStat = item.stat;
            let upDetailsList = item.upDetailsList;
            let upStrs = [];
            upDetailsList.forEach(ele => {
              upStrs.push(ele.goodsName + ' X' + ele.deliverNum);
            })
            let str = upStrs.join('、');
            pack.packGoodsStrs = str;
            packs.push(pack);
          })
          e.packs = packs;
        })
      }
      if (that.data.pageNum > 1) {
        goodsApplyList = that.data.goodsApplyList.concat(goodsApplyList);
      }
      let applyStatus = that.data.applyStatus
      applyStatus.forEach(item => {
        let num = countMap['apply' + item.id]
        if (num >= 0) {
          item.num = num
        }
      })
      console.log("goodsApplyList=======", goodsApplyList)
      that.setData({
        goodsApplyList: goodsApplyList,
        applyStatus: applyStatus
      });
    });

  },
  copyPackInfo: function (e) {
    let pack = e.target.dataset.pack;
    let str = '';
    str += pack.packName + '：' + (pack.packStat == 1 ? '已收货' : '待收货') + '\n';
    str += '发货物品：' + pack.packGoodsStrs + '\n';
    wx.setClipboardData({
      data: str,
      success: function (res) {
        wx.getClipboardData({
          success: function (res) {
            wx.showToast({
              title: '复制成功',
            })
          }
        })
      }
    })

  },
  hprtPrint: function (e) {
    let item = e.target.dataset.item;
    this.data.allPrintData = item;
    this.getPrintContent(item);
    this.setData({
      hideFlag: false
    })

  },
  //获取需要打印的地址信息
  getPrintAddrContent: function (item, y) {
    let str = '';
    let lineCounts = 0;
    let lineHeight = 30,
      startX = 10,
      firstLineLen = 30,
      secondLineLen = 16,
      xM = 1,
      yM = 1,
      font = 1;
    if (this.data.printSelContents.length == 1) {
      xM = 2;
      yM = 2;
      font = 0;
      firstLineLen = 11;
      secondLineLen = 10;
      lineHeight = 60;
    }
    let applyUserStr = '收货人:' + item.applyUserName;
    let rstTxt = printUtil.txtHandle(applyUserStr, lineHeight, y, startX, firstLineLen, secondLineLen, xM, yM, font);
    str += rstTxt.str;
    y = rstTxt.y;
    lineCounts += rstTxt.lineCounts;

    if (item.receivePerson) {
      let receivePerson = '收货人名称:' + item.receivePerson;
      let rstTxt = printUtil.txtHandle(receivePerson, lineHeight, y, startX, firstLineLen, secondLineLen, xM, yM, font);
      str += rstTxt.str;
      y = rstTxt.y;
      lineCounts += rstTxt.lineCounts;
    }
    if (item.receivePhone) {
      let receivePhone = '收货人手机:' + item.receivePhone;
      let startX = 10;
      let firstLineLen = 20;
      let rstTxt = printUtil.txtHandle(receivePhone, lineHeight, y, startX, firstLineLen, secondLineLen, xM, yM, font);
      str += rstTxt.str;
      y = rstTxt.y;
      lineCounts += rstTxt.lineCounts;
    }
    if (item.receiveAddress) {
      let txt = '收货地址:' + item.receiveAddress;
      let rstTxt = printUtil.txtHandle(txt, lineHeight, y, startX, firstLineLen, secondLineLen, xM, yM, font);
      str += rstTxt.str;
      y = rstTxt.y;
      lineCounts += rstTxt.lineCounts;
    }
    return {
      "str": str,
      "y": y,
      "lineCounts": lineCounts
    };
  },
  //获取需要打印的内容
  getPrintContent: function (item) {
    app.globalData.printNextPageStr = "";
    let str = '';
    let lineAddrCounts = 0;
    let lineGoodsCounts = 0;
    let onePageLineGoodsCount = 0;
    let lineHeight = 40;
    let headHeight = 110;
    let y = headHeight; //留出打印时间及份数的数据

    let selContents = this.data.printSelContents;
    if (selContents.indexOf(this.data.printSleAddr) != -1) {
      let rstTxt = this.getPrintAddrContent(item, y);
      str += rstTxt.str;
      y = rstTxt.y;
      lineAddrCounts = rstTxt.lineCounts;
    }
    if (lineAddrCounts > 0) {
      onePageLineGoodsCount = 15 - Math.ceil(lineAddrCounts / 2);
    } else {
      onePageLineGoodsCount = 15;
    }
    console.log("地址与物品的行数", onePageLineGoodsCount, lineAddrCounts);
    if (selContents.indexOf(this.data.printSelApply) != -1) {
      let goodsArr = item.goodsStrs.split("、");
      let txt = '申请物品:';
      let rstTxt = printUtil.txtHandle(txt, lineHeight, y);
      str += rstTxt.str;
      y = rstTxt.y;
      let xM = 3;
      let yM = 3;
      let font = "1";
      let goodsLineHeight = 60;
      let firstLineLen = 12;
      let secondLineLen = 11;
      let startX = 35;
      let isNextPage = false;
      for (var i = 0; i < goodsArr.length; i++) {
        let goodsTxt = (i + 1) + '.' + goodsArr[i];
        let oneGoodsLineCount = 0;
        if (onePageLineGoodsCount >= lineGoodsCounts) {
          let rstTxt = printUtil.txtHandle(goodsTxt, goodsLineHeight, y, startX, firstLineLen, secondLineLen, xM, yM, font);
          str += rstTxt.str;
          y = rstTxt.y;
          oneGoodsLineCount = rstTxt.lineCounts;
        } else {
          if (!isNextPage) {
            y = headHeight;
            isNextPage = true;
          }
          let rstTxt = printUtil.txtHandle(goodsTxt, goodsLineHeight, y, startX, firstLineLen, secondLineLen, xM, yM, font);
          app.globalData.printNextPageStr += rstTxt.str;
          y = rstTxt.y;
          oneGoodsLineCount = rstTxt.lineCounts;
        }
        lineGoodsCounts += oneGoodsLineCount;
      }
      console.log("物品的行数", lineGoodsCounts, goodsArr.length);
    }

    if (str == '') {
      wx.showModal({
        title: '提示',
        content: '没有选择要打印的内容',
      })
    }
    this.data.lineAddrCounts = lineAddrCounts;
    this.data.lineGoodsCounts = lineGoodsCounts;
    this.data.printContent = str;
  },
  sufNumInp: function (e) {
    let sufNum = e.detail.value;
    this.setData({
      sufNum: sufNum
    })
  },
  hideModal: function () {
    this.setData({
      hideFlag: true
    });
  },
  stopMaoPao: function () {
    return true;
  },
  checkSubmit: function (e) {
    let that = this;
    if (that.data.sufNum !== '0') {
      var r = /^\+?[1-9][0-9]*$/;
      if (!r.test(that.data.sufNum)) {
        that.toast.showToast('请输入大于0的整数');
        return false;
      }
    }

    printUtil.print(that.data.printContent, that.data.sufNum, that.data.lineAddrCounts, that.data.lineGoodsCounts);
    that.setData({
      hideFlag: true,
      sufNum: 1
    })

  },
  copyGoodsInfo: function (e) {
    let item = e.target.dataset.item;
    wx.setClipboardData({
      data: item.goodsStrs,
      success: function (res) {
        wx.getClipboardData({
          success: function (res) {
            wx.showToast({
              title: '复制成功',
            })
          }
        })
      }
    })

  },
  copyReceive: function (e) {
    let item = e.target.dataset.item;
    let str = '';
    // str += '收货人：' + item.applyUserName + '\n';
    if (item.receivePerson)
      str += '收货人：' + item.receivePerson + '\n';
    if (item.receivePhone)
      str += '收货人联系方式：' + item.receivePhone + '\n';
    if (item.receiveAddress)
      str += '收货人地址：' + item.receiveAddress + '\n';
    // str += '申请物品：' + item.goodsStrs + '\n';
    wx.setClipboardData({
      data: str,
      success: function (res) {
        wx.getClipboardData({
          success: function (res) {
            wx.showToast({
              title: '复制成功',
            })
          }
        })
      }
    })
  },
  checkboxPrintSelChange: function (e) {
    console.log("打印内容选择打印", e);
    this.data.printSelContents = e.detail.value;
    if (!this.data.printSelContents || this.data.printSelContents.length == 0) {
      wx.showModal({
        title: '提示',
        content: '请选择至少一个要打印的内容',
      })
    } else {
      this.getPrintContent(this.data.allPrintData);
    }
  }
})